import os
import logging
import pickle

from google.appengine.api import users

from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http
from django import shortcuts

import views

from models import Greeting
from models import Website
from models import WebsiteForm

def test(request):
  data = request.session.get('data');
  logging.info('current data: %s' % data)
  storethis = {'fuck': {
    'yeah': 'bitch',
    'eatme': 'turd'
  }}
  request.session['data'] = storethis
  return http.HttpResponse('data: %s' % data)

def index(request):
  """Request / -- show all websites."""
  user = users.GetCurrentUser()
  websites = db.GqlQuery("SELECT * "
                          "FROM Website "
                          "ORDER BY created DESC LIMIT 50")
  return views.respond(request, user, 'websites/index', {'websites': websites})


def edit(request, website_id):
  """Create or edit a website.  GET shows a blank form, POST processes it."""
  user = users.GetCurrentUser()
  form = None
  website = None
  if website_id:
    website = Website.get(db.Key.from_path(Website.kind(), int(website_id)))
    if website is None:
      return http.HttpResponseNotFound('No website exists with that key (%r)' %
                                       website_id)
  
  
  if request.POST:
    form_data = request.POST
  elif request.session.get('website_form'):
    form_data = pickle.loads(request.session.get('website_form'))
    logging.info('form_data from session: %s' % form_data)
  else:
    form_data = None
  form = WebsiteForm(data=form_data, instance=website)
    
  # Now reset our session data because we've gotten it once if it was there.
  request.session['website_form'] = None
  
  # Basic GET request
  if not request.POST:
    return views.respond(request, user, 'websites/form', 
                         {'form': form, 'website': website})
    
  # Look for form errors
  errors = form.errors
  if not errors:
    try:
      website = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return views.respond(request, user, 'websites/form', 
                         {'form': form, 'website': website})
  
  # They've clicked save, but not signed in..
  if user is None:
    # Store the current request in session so that we can resubmit after login.
    # We need to pickle the QueryDict object first though.
    website_form_data = pickle.dumps(request.POST)
    request.session['website_form'] = website_form_data
    logging.info('***** Stored request.POST in session! %s' % website_form_data)
    
    # Now make them login.
    login_url = users.create_login_url(request.get_full_path())
    return http.HttpResponseRedirect(login_url)
    
  # We have a user object, so attach that to the website instance.
  website.owner = user
  
  website.put()
  
  url = '/websites/view/%s' % website.key().id()
  return http.HttpResponseRedirect(url)
  

def create(request):
  """Create a website.  GET shows a blank form, POST processes it."""
  return edit(request, None)
  
  
def view(request, website_id, page=1):
  """View a website.  GET shows a blank form, POST processes it."""
  
  count = 10
  
  user = users.GetCurrentUser()
  
  if website_id is None:
    return http.HttpResponseNotFound('No website exists with that key')
    
  website = Website.get(db.Key.from_path(Website.kind(), int(website_id)))
  if website is None:
    return http.HttpResponseNotFound('No website exists with that key (%r)' %
                                     website_id)
  
  query = db.Query(Greeting)
  query.filter('website =', website)
  query.order('-created')
  offset = (page-1)*count
  website.greetings = query.fetch(10, offset)
  logging.info('greetings: %s' % website.greetings)
  
  template = 'websites/view'
  if request.has_key('output') and request['output'] == 'rss':
    template = template + '_rss'
    
  return views.respond(request, user, template, {'website': website})  

